<template>
  <div class="survey-page">
    <div class="navbar">
      <div class="nav-back" @click="goBack">
        <i class="fas fa-chevron-left"></i>
      </div>
      <div class="nav-title">自评量表</div>
      <div class="nav-placeholder"></div>
    </div>

    <!-- 进度条 -->
    <div class="progress-section">
      <div class="progress-bar">
        <div
          class="progress"
          :style="{
            width: ((currentIndex + 1) / questions.length) * 100 + '%',
          }"
        ></div>
      </div>
      <div class="progress-text">
        第 {{ currentIndex + 1 }} / {{ questions.length }} 题
        <span v-if="currentPart !== 'initial'"> - 第{{ currentPart }}部分</span>
      </div>
    </div>
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <div v-else class="content">
      <div v-if="currentQuestion">
        <!-- 进度条 -->
        <div class="progress-section">
          <div class="progress-bar">
            <div
              class="progress"
              :style="{
                width: ((currentIndex + 1) / questions.length) * 100 + '%',
              }"
            ></div>
          </div>
          <div class="progress-text">
            第 {{ currentIndex + 1 }} / {{ questions.length }} 题
            <span v-if="currentPart !== 'initial'">
              - 第{{ currentPart }}部分</span
            >
          </div>
        </div>

        <!-- 题目卡片 -->
        <div class="question-card">
          <!-- 大标题 -->

          <div
            class="question-title"
            v-if="currentQuestion.subject == '1.\t您是否经常感到紧张?'"
          >
            最近一个月，您是否被以下问题困扰，选择最符合您情况的选项。
          </div>
          <div
            class="question-title"
            v-if="currentQuestion.subject == '1.感觉紧张，焦虑或急切'"
          >
            一、在过去的两周里，你生活中以下症状出现的频率有多少？
          </div>

          <div
            class="question-title"
            v-if="currentQuestion.subject == '1.做事时提不起劲或没有兴趣'"
          >
            二、在过去的两周里，你生活中以下症状出现的频率有多少？
          </div>

          <div
            class="question-title"
            v-if="currentQuestion.subject == '1.容易烦恼和激动。'"
          >
            三丶以下列出了有些人可能会有的问题，根据最近一周以内下述情况影响您的实际感觉，选择合适的选项。
          </div>

          <div
            class="question-title"
            v-if="
              currentQuestion.subject ==
              '1.\t近1个月，总体来说，您认为您的睡眠质量？ '
            "
          >
            五、请根据您的实际情况选择符合的选项。
          </div>
          <div
            class="question-title"
            v-if="
              currentQuestion.subject ==
              '1.因为一些无法预期的事情发生而感到心烦意乱。'
            "
          >
            六、最近[一个月]来，下列事情发生你身上的频率如何？
          </div>
          <div
            class="question-title"
            v-if="currentQuestion.subject == '1.工作让我感觉身心俱惫。'"
          >
            五、请根据题目描述，选择最符合您当前情况的描述。
          </div>

          <div
            class="question-title"
            v-if="
              currentQuestion.subject == '1.过去两周，我感觉快乐、心情舒畅。'
            "
          >
            六、请选择在过去两星期最接近您感觉的状态。
          </div>
          <div
            class="question-title"
            v-if="
              currentQuestion.subject ==
              '1.\t有过自伤行为（如用手打墙、摔东西） '
            "
          >
            最近半年，您有过下列行为吗？
          </div>

          <!-- 大标题 -->
          <div class="question-title">{{ currentQuestion.subject }}</div>

          <!-- 单选题 -->
          <div v-if="currentQuestion.type === 'radio'" class="options">
            <div
              v-for="item in currentQuestion.item"
              :key="item.id"
              class="option"
              :class="{ selected: getAnswer(currentQuestion.id) === item.id }"
              @click="selectOption(item)"
            >
              <div class="option-indicator">
                <div class="option-circle"></div>
              </div>
              <div class="option-text">{{ item.name }}</div>
            </div>
          </div>

          <!-- 下拉选择题 -->
          <div
            v-else-if="currentQuestion.type === 'select'"
            class="select-container"
          >
            <select
              v-model="answers[currentQuestion.id]"
              class="custom-select"
              @change="onAnswerChange"
            >
              <option value="">请选择</option>
              <option
                v-for="item in currentQuestion.item"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </option>
            </select>
          </div>

          <!-- 输入题 -->
          <div
            v-else-if="currentQuestion.type === 'input'"
            class="input-container"
          >
            <input
              type="text"
              v-model="answers[currentQuestion.id]"
              placeholder="请输入"
              class="custom-input"
              @input="onAnswerChange"
            />
          </div>

          <!-- 多选题 -->
          <div
            v-else-if="currentQuestion.type === 'checkbox'"
            class="options checkbox-options"
          >
            <div
              v-for="item in currentQuestion.item"
              :key="item.id"
              class="option checkbox-option"
              :class="{ selected: isCheckboxSelected(item) }"
              @click="toggleCheckboxOption(item)"
            >
              <div class="option-indicator">
                <div class="checkbox-square">
                  <div class="checkmark" v-if="isCheckboxSelected(item)">✓</div>
                </div>
              </div>
              <div class="option-text">{{ item.name }}</div>
            </div>
          </div>

          <!-- 导航按钮 -->
          <div class="navigation-buttons">
            <button
              v-if="currentIndex > 0"
              class="nav-btn prev-btn"
              @click="prevQuestion"
            >
              上一题
            </button>
            <button
              v-if="currentIndex < questions.length - 1"
              class="nav-btn next-btn"
              @click="nextQuestion"
              :disabled="!hasAnswerForCurrentQuestion"
            >
              下一题
            </button>
            <button
              v-else
              class="nav-btn submit-btn"
              @click="submitAnswers"
              :disabled="!hasAnswerForCurrentQuestion"
            >
              {{ isLastPart ? "提交答案" : "下一部分" }}
            </button>
          </div>
        </div>
      </div>

      <div v-else-if="questions.length === 0 && !loading">
        <!-- 答题完成 -->
        <div class="finished-card">
          <div class="success-icon">✓</div>
          <h2>答题完成，谢谢！</h2>
          <p class="completion-text">您已完成所有题目，感谢您的参与。</p>
          <button class="view-report-btn" @click="viewReport">查看报告</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  startSurvey,
  partOneCalculation,
  nextPart,
  otherPartAnswerSave,
  checkPHQ9,
} from "@/api/CP";

export default {
  data() {
    return {
      loading: true,
      questions: [],
      currentIndex: 0,
      answers: {},
      startTime: "",
      parts: [],
      votelogId: null,
      currentPart: "initial", // 'initial' 或 part编号
      partIndex: 0,
      unitId: null,
      hasCheckedPHQ9: false, // 标记是否已经检查过PHQ9
      isSelecting: false, // 防止重复点击的标志
    };
  },
  computed: {
    currentQuestion() {
      return this.questions[this.currentIndex] || null;
    },
    isLastQuestion() {
      return this.currentIndex === this.questions.length - 1;
    },
    isLastPart() {
      return this.partIndex >= this.parts.length;
    },
    hasAnswerForCurrentQuestion() {
      if (!this.currentQuestion) return false;

      const answer = this.getAnswer(this.currentQuestion.id);

      // 多选题：至少选了一个
      if (this.currentQuestion.type === "checkbox") {
        return answer && answer.length > 0;
      }

      // 下拉题：若选择值为 "0"，视为未作答
      if (this.currentQuestion.type === "select") {
        return answer !== "" && answer !== "0";
      }

      // 其他类型：只要有值即可
      return !!answer;
    },
  },
  methods: {
    // 查询是否做答第9部分的问卷
    getcheckPHQ9() {
      return new Promise((resolve, reject) => {
        checkPHQ9({
          votelogId: this.votelogId,
        })
          .then((res) => {
            if (res.code === 200) {
              resolve(res.data); // 返回true或false
            } else {
              console.error("检查PHQ9失败:", res);
              reject(new Error(res.message || "检查PHQ9失败"));
            }
          })
          .catch((err) => {
            console.error("检查PHQ9异常:", err);
            reject(err);
          });
      });
    },

    getAnswer(questionId) {
      return this.answers[questionId];
    },

    onAnswerChange() {
      this.$forceUpdate();
    },

    getstartSurvey() {
      this.startTime = new Date().toISOString().replace("T", " ").split(".")[0];
      this.unitId = localStorage.getItem("unitId") || "defaultUnitId";

      startSurvey()
        .then((res) => {
          if (res.code === 200 && res.data) {
            this.questions = res.data;
            this.currentPart = "initial";
            this.initializeAnswers();
          } else {
            console.error("获取题目失败:", res);
            this.$toast?.("获取题目失败，请重试");
          }
        })
        .catch((err) => {
          console.error("获取题目异常:", err);
          this.$toast?.("网络错误，请重试");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 初始化答案
    initializeAnswers() {
      this.answers = {};
      this.questions.forEach((question) => {
        if (question.type === "checkbox") {
          this.$set(this.answers, question.id, []);
        } else {
          this.$set(this.answers, question.id, "");
        }
      });
    },

    // 检查checkbox选项是否被选中
    isCheckboxSelected(item) {
      const questionId = this.currentQuestion.id;
      const answer = this.answers[questionId];
      return answer && answer.includes(item.id);
    },

    // 切换checkbox选项
    toggleCheckboxOption(item) {
      const questionId = this.currentQuestion.id;

      if (!this.answers[questionId]) {
        this.$set(this.answers, questionId, []);
      }

      const currentAnswers = this.answers[questionId];
      const optionIndex = currentAnswers.indexOf(item.id);

      if (optionIndex > -1) {
        currentAnswers.splice(optionIndex, 1);
      } else {
        currentAnswers.push(item.id);
      }

      this.$set(this.answers, questionId, [...currentAnswers]);
    },

    selectOption(item) {
      if (this.isSelecting) return; // 如果正在选择中，直接返回

      this.isSelecting = true;
      this.$set(this.answers, this.currentQuestion.id, item.id);

      setTimeout(() => {
        if (this.currentIndex < this.questions.length - 1) {
          this.currentIndex += 1;
        }
        this.isSelecting = false; // 重置状态
      }, 200);
    },

    nextQuestion() {
      if (!this.hasAnswerForCurrentQuestion) {
        this.$toast?.("请先完成当前题目");
        return;
      }

      if (this.currentIndex < this.questions.length - 1) {
        this.currentIndex += 1;
      }
    },

    prevQuestion() {
      if (this.currentIndex > 0) {
        this.currentIndex -= 1;
      }
    },

    submitAnswers() {
      if (!this.hasAnswerForCurrentQuestion) {
        this.$toast?.("请先完成当前题目");
        return;
      }

      // 构建答案数组 - 现在存储的是id而不是name
      const dataArr = this.questions.map((q) => {
        const answer = this.answers[q.id];

        if (q.type === "checkbox") {
          return Array.isArray(answer) ? answer.join(",") : "";
        }

        // ✅ 保留字符串 "0"
        return answer === undefined || answer === null ? "" : String(answer);
      });

      console.log("提交数据:", dataArr);

      if (this.currentPart === "initial") {
        console.log("提交初始部分...");
        const userId = localStorage.getItem("userId") || "unknown";
        const payload = {
          userId,
          starttime: this.startTime,
          data: dataArr,
        };

        partOneCalculation(payload)
          .then((res) => {
            console.log("partOneCalculation返回:", res);
            if (res.code === 200 && res.data) {
              this.parts = res.data.parts || [];

              localStorage.setItem(
                "partOneScore",
                JSON.stringify(res.data.partOneScore)
              );
              this.votelogId = res.data.votelogId;

              console.log("下一部分列表:", this.parts);

              if (this.parts.length > 0) {
                this.startNextPart();
              } else {
                // 如果没有parts，检查是否需要做第9部分
                this.checkAndLoadPHQ9();
              }
            } else {
              console.error("partOneCalculation返回错误:", res);
              this.$toast?.("提交失败: " + (res.message || "未知错误"));
            }
          })
          .catch((err) => {
            console.error("partOneCalculation请求错误:", err);
            this.$toast?.("网络错误，请重试");
          });
      } else {
        console.log(`提交第${this.currentPart}部分...`);

        const payload = {
          part: this.currentPart,
          data: dataArr,
          unitId: localStorage.getItem("unitId"),
          userId: localStorage.getItem("userId"),
          votelogId: this.votelogId,
        };

        otherPartAnswerSave(payload)
          .then((res) => {
            console.log(`第${this.currentPart}部分保存结果:`, res);
            if (res.code === 200) {
              if (!this.isLastPart) {
                this.startNextPart();
              } else {
                // 所有parts都完成了，检查是否需要做第9部分
                this.checkAndLoadPHQ9();
              }
            } else {
              console.error("保存答案失败:", res);
              this.$toast?.("保存答案失败: " + (res.message || "未知错误"));
            }
          })
          .catch((err) => {
            console.error("保存答案请求错误:", err);
            this.$toast?.("网络错误，请重试");
          });
      }
    },

    // 检查并加载PHQ9问卷
    checkAndLoadPHQ9() {
      if (this.hasCheckedPHQ9) {
        // 如果已经检查过，直接结束
        this.questions = [];
        this.$toast?.("所有部分答题完成！");
        return;
      }

      console.log("检查是否需要做第9部分问卷...");
      this.hasCheckedPHQ9 = true;

      this.getcheckPHQ9()
        .then((needPHQ9) => {
          if (needPHQ9) {
            console.log("需要做第9部分问卷");
            this.loadPHQ9Part();
          } else {
            console.log("不需要做第9部分问卷");
            this.questions = [];
            this.$toast?.("所有部分答题完成！");
          }
        })
        .catch((err) => {
          console.error("检查PHQ9失败:", err);
          this.$toast?.("检查失败，直接结束答题");
          this.questions = [];
        });
    },

    // 加载第9部分问卷
    loadPHQ9Part() {
      console.log("开始获取第9部分题目");
      this.loading = true;

      nextPart({ part: 9 })
        .then((res) => {
          console.log("第9部分返回:", res);
          if (res.code === 200 && res.data) {
            this.questions = res.data;
            this.currentIndex = 0;
            this.currentPart = 9; // 设置当前部分为9
            this.initializeAnswers();
            console.log(`第9部分题目加载成功，共${res.data.length}题`);
          } else {
            console.error("获取第9部分失败:", res);
            this.$toast?.("加载第9部分题目失败");
            this.questions = [];
          }
        })
        .catch((err) => {
          console.error("获取第9部分异常:", err);
          this.$toast?.("网络错误，请重试");
          this.questions = [];
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 开始下一部分
    startNextPart() {
      if (this.partIndex < this.parts.length) {
        const nextPartNumber = this.parts[this.partIndex];
        this.currentPart = nextPartNumber;

        console.log(`开始获取第${nextPartNumber}部分题目`);

        this.loading = true;
        nextPart({ part: nextPartNumber })
          .then((res) => {
            console.log(`第${nextPartNumber}部分返回:`, res);
            if (res.code === 200 && res.data) {
              this.questions = res.data;
              this.currentIndex = 0;
              this.initializeAnswers();
              this.partIndex += 1;

              console.log(
                `第${nextPartNumber}部分题目加载成功，共${res.data.length}题`
              );
            } else {
              console.error(`获取第${nextPartNumber}部分失败:`, res);
              this.$toast?.("加载题目失败: " + (res.message || "未知错误"));
            }
          })
          .catch((err) => {
            console.error(`获取第${nextPartNumber}部分异常:`, err);
            this.$toast?.("网络错误，请重试");
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },

    // 查看报告
    viewReport() {
      if (this.votelogId) {
        // 跳转到报告页面，使用votelogId作为参数
        this.$router.push({
          path: "/CP/Report",
          query: { votelogId: this.votelogId },
        });
      } else {
        this.$toast?.("无法查看报告，缺少必要参数");
      }
    },

    goBack() {
      window.history.back();
    },
  },
  created() {
    this.getstartSurvey();
  },
};
</script>

<style scoped>
/* 样式保持不变，与之前相同 */
.survey-page {
  max-width: 500px;
  margin: 0 auto;
  color: #333;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4efe9 100%);
  min-height: 100vh;
}
.navbar {
  max-width: 500px;
  margin: 0 auto;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
  z-index: 1000;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.nav-back {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6366f1;
  border: none;
  cursor: pointer;
}

.nav-back:hover {
  background: #eef0ff;
}
.nav-title {
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.nav-placeholder {
  width: 40px;
}

.loading {
  text-align: center;
  margin-top: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.spinner {
  width: 50px;
  height: 50px;
  border: 5px solid rgba(79, 172, 254, 0.2);
  border-radius: 50%;
  border-top-color: #4facfe;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 15px;
}
@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.progress-section {
  margin-bottom: 25px;
}
.progress-bar {
  width: 100%;
  height: 8px;
  background-color: #e0e0e0;
  border-radius: 4px;
  margin-bottom: 10px;
  overflow: hidden;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
}
.progress {
  height: 100%;
  background: linear-gradient(to right, #4facfe, #00f2fe);
  transition: width 0.5s ease;
  border-radius: 4px;
}
.progress-text {
  text-align: center;
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.question-card {
  background-color: #fff;
  padding: 30px;
  border-radius: 20px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
  transition: transform 0.3s ease;
}
.question-card:hover {
  transform: translateY(-5px);
}
.question-title {
  font-size: 22px;
  margin-bottom: 25px;
  line-height: 1.5;
  font-weight: 600;
  color: #2c3e50;
}

.options {
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-height: 30vh;
}
.option {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  background: #f8fafc;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.2s ease;
}
.option:hover {
  background: #f1f5f9;
  border-color: #cbd5e1;
}
.option.selected {
  background: #e3f2fd;
  border-color: #4facfe;
}
.option-indicator {
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.option-circle {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 2px solid #cbd5e1;
  transition: all 0.2s ease;
}
.option.selected .option-circle {
  border-color: #4facfe;
  background-color: #4facfe;
  box-shadow: 0 0 0 4px rgba(79, 172, 254, 0.2);
}

/* Checkbox 特定样式 */
.checkbox-options {
  max-height: 400px;
  overflow-y: auto;
}
.checkbox-option {
  align-items: flex-start;
}
.checkbox-square {
  width: 20px;
  height: 20px;
  border: 2px solid #cbd5e1;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  margin-top: 2px;
}
.checkbox-option.selected .checkbox-square {
  border-color: #4facfe;
  background-color: #4facfe;
}
.checkmark {
  color: white;
  font-size: 14px;
  font-weight: bold;
}

.option-text {
  flex: 1;
  line-height: 1.4;
}

.select-container,
.input-container {
  margin-bottom: 20px;
  min-height: 30vh;
}
.custom-select,
.custom-input {
  width: 100%;
  padding: 16px 20px;
  font-size: 16px;
  border-radius: 12px;
  border: 2px solid #e2e8f0;
  background-color: #fff;
  transition: all 0.2s ease;
  box-sizing: border-box;
}
.custom-select:focus,
.custom-input:focus {
  outline: none;
  border-color: #4facfe;
  box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.2);
}
.custom-select {
  appearance: none;
  background-image: url("data:image/svg+xml;charset=US-ASCII,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'><path fill='%23666' d='M2 0L0 2h4zm0 5L0 3h4z'/></svg>");
  background-repeat: no-repeat;
  background-position: right 15px center;
  background-size: 10px;
}

.navigation-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
}
.nav-btn {
  padding: 14px 28px;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s ease;
}
.prev-btn {
  background: #f8fafc;
  color: #64748b;
  border: 2px solid #e2e8f0;
}
.prev-btn:hover {
  background: #f1f5f9;
  border-color: #cbd5e1;
}
.next-btn,
.submit-btn {
  background: linear-gradient(to right, #4facfe, #00f2fe);
  color: white;
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.3);
}
.next-btn:hover,
.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(79, 172, 254, 0.4);
}
.next-btn:disabled,
.submit-btn:disabled {
  background: #cbd5e1;
  transform: none;
  box-shadow: none;
  cursor: not-allowed;
}

.finished-card {
  text-align: center;
  margin-top: 60px;
  background: #fff;
  padding: 50px 30px;
  border-radius: 20px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08);
}
.success-icon {
  width: 80px;
  height: 80px;
  background: linear-gradient(to right, #4facfe, #00f2fe);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40px;
  margin: 0 auto 25px;
  box-shadow: 0 6px 20px rgba(79, 172, 254, 0.3);
}
.finished-card h2 {
  font-size: 28px;
  margin-bottom: 15px;
  color: #2c3e50;
}
.completion-text {
  font-size: 16px;
  color: #64748b;
  margin-bottom: 30px;
}

/* 查看报告按钮 */
.view-report-btn {
  background: linear-gradient(to right, #4facfe, #00f2fe);
  color: white;
  border: none;
  padding: 14px 28px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.3);
}
.view-report-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(79, 172, 254, 0.4);
}

.content {
  padding: 20px;
  box-sizing: border-box;
  max-width: 800px;
  margin: 0 auto;
}

@media (max-width: 600px) {
  .content {
    padding: 15px;
  }
  .question-card {
    padding: 20px;
  }
  .question-title {
    font-size: 20px;
  }
  .navigation-buttons {
    flex-direction: column;
    gap: 10px;
  }
  .nav-btn {
    width: 100%;
  }
  .checkbox-options {
    max-height: 300px;
  }
}
</style>
